/*
 *
 *  * | Licensed 未经许可不能去掉「OPENIITA」相关版权
 *  * +----------------------------------------------------------------------
 *  * | Author: xw2sy@163.com
 *  * +----------------------------------------------------------------------
 *
 *  Copyright [2024] [OPENIITA]
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 * /
 */

package cc.iotkit.data.service;

import cc.iotkit.common.api.PageRequest;
import cc.iotkit.common.api.Paging;
import cc.iotkit.common.satoken.utils.LoginHelper;
import cc.iotkit.common.utils.MapstructUtils;
import cc.iotkit.common.utils.StringUtils;
import cc.iotkit.data.dao.DeviceInfoPartsRepository;
import cc.iotkit.data.dao.IJPACommData;
import cc.iotkit.data.manager.IDeviceInfoPartsData;
import cc.iotkit.data.model.TbDeviceGroup;
import cc.iotkit.data.model.TbDeviceInfoParts;
import cc.iotkit.data.model.TbDeviceParts;
import cc.iotkit.data.util.PredicateBuilder;
import cc.iotkit.model.device.DeviceGroup;
import cc.iotkit.model.device.DeviceInfoParts;
import cc.iotkit.model.device.DeviceParts;
import com.querydsl.core.QueryResults;
import com.querydsl.core.types.Predicate;
import com.querydsl.core.types.Projections;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

import static cc.iotkit.data.model.QTbBasMaintenanceUnit.tbBasMaintenanceUnit;
import static cc.iotkit.data.model.QTbDeviceInfoParts.tbDeviceInfoParts;
import static cc.iotkit.data.model.QTbDeviceParts.tbDeviceParts;

@Primary
@Service
public class DeviceInfoPartsDataImpl implements IDeviceInfoPartsData, IJPACommData<DeviceInfoParts, Long> {
    @Autowired
    private JPAQueryFactory jpaQueryFactory;
    @Autowired
    private DeviceInfoPartsRepository repository;

    @Override
    public JpaRepository getBaseRepository() {
        return repository;
    }

    @Override
    public Class getJpaRepositoryClass() {
        return TbDeviceInfoParts.class;
    }

    @Override
    public Class getTClass() {
        return DeviceInfoParts.class;
    }



    @Override
    public DeviceInfoParts findById(Long s) {
        return MapstructUtils.convert(repository.findById(s).orElse(null), DeviceInfoParts.class);
    }

    @Override
    public DeviceInfoParts save(DeviceInfoParts data) {
        if (data.getId()==null||data.getId().equals(0L)) {
            data.setUid(LoginHelper.getUserId());
            data.setCreateAt(System.currentTimeMillis());
            data.setCreateBy(LoginHelper.getUserId());
        }else{
            data.setUpdateAt(System.currentTimeMillis());
            data.setUpdateBy(LoginHelper.getUserId());
        }
        repository.save(MapstructUtils.convert(data, TbDeviceInfoParts.class));
        return data;
    }

    @Transactional
    public List<DeviceInfoParts> saveAll(List<DeviceInfoParts> datas) {
        for(DeviceInfoParts data : datas){
            if (data.getId()==null||data.getId().equals(0L)) {
                data.setUid(LoginHelper.getUserId());
                data.setCreateAt(System.currentTimeMillis());
                data.setCreateBy(LoginHelper.getUserId());
            }else{
                data.setUpdateAt(System.currentTimeMillis());
                data.setUpdateBy(LoginHelper.getUserId());
            }
        }

        List<TbDeviceInfoParts> results= repository.saveAll(MapstructUtils.convert(datas, TbDeviceInfoParts.class));
        return MapstructUtils.convert(results, DeviceInfoParts.class);
    }

    @Override
    public List<DeviceInfoParts> findAll() {
        return MapstructUtils.convert(repository.findAll(), DeviceInfoParts.class);
    }
    private Predicate buildPredicate(DeviceInfoParts data) {
        return PredicateBuilder.instance()
                .and(data.getId()!=null,()->tbDeviceInfoParts.id.eq(data.getDevicePartsId()))
                .and(data.getDevicePartsId()!=null, () -> tbDeviceInfoParts.devicePartsId.eq(data.getDevicePartsId()))
                .and(StringUtils.isNotEmpty(data.getDeviceId()), () -> tbDeviceInfoParts.deviceId.eq(data.getDeviceId()))
                .build();
    }
    public List<DeviceInfoParts> findAllByCondition(DeviceInfoParts query) {
        Predicate predicate = buildPredicate(query);
        List<DeviceInfoParts> results = jpaQueryFactory.select(Projections.bean(DeviceInfoParts.class,
                        tbDeviceInfoParts.id,tbDeviceInfoParts.remark,tbDeviceInfoParts.updateAt,tbDeviceInfoParts.updateBy,tbDeviceInfoParts.qty,
                        tbDeviceInfoParts.devicePartsId,tbDeviceInfoParts.deviceId,tbDeviceInfoParts.createDept,tbDeviceInfoParts.uid,
                        tbDeviceInfoParts.createAt,tbDeviceInfoParts.createBy,tbDeviceInfoParts.remark,tbDeviceParts.partCode,tbDeviceParts.partName,
                        tbDeviceParts.maintenancePeriod,tbDeviceParts.unitId,tbBasMaintenanceUnit.unitName))
                .from(tbDeviceInfoParts)
                .leftJoin(tbDeviceParts).on(tbDeviceInfoParts.devicePartsId.eq(tbDeviceParts.id))
                .leftJoin(tbBasMaintenanceUnit).on(tbDeviceParts.unitId.eq(tbBasMaintenanceUnit.id))
                .where(predicate).fetch();
        return results;

    }
    public Paging<DeviceInfoParts> findAllByConditions(PageRequest<DeviceInfoParts> pageRequest) {
        DeviceInfoParts data = pageRequest.getData();
        Predicate predicate = buildPredicate(data);
        QueryResults<DeviceInfoParts> results = jpaQueryFactory.select(Projections.bean(DeviceInfoParts.class,
                        tbDeviceInfoParts.id,tbDeviceInfoParts.remark,tbDeviceInfoParts.updateAt,tbDeviceInfoParts.updateBy,tbDeviceInfoParts.qty,
                        tbDeviceInfoParts.devicePartsId,tbDeviceInfoParts.deviceId,tbDeviceInfoParts.createDept,tbDeviceInfoParts.uid,
                        tbDeviceInfoParts.createAt,tbDeviceInfoParts.createBy,tbDeviceInfoParts.remark,tbDeviceParts.partCode,tbDeviceParts.partName,
                        tbDeviceParts.maintenancePeriod,tbDeviceParts.unitId,tbBasMaintenanceUnit.unitName))
                .from(tbDeviceInfoParts)
                .leftJoin(tbDeviceParts).on(tbDeviceInfoParts.devicePartsId.eq(tbDeviceParts.id))
                .leftJoin(tbBasMaintenanceUnit)
                .where(predicate).limit(pageRequest.getPageSize()).offset(pageRequest.getOffset()).fetchResults();
        return new Paging<>(results.getTotal(), results.getResults());

    }
}
